import { Repository } from './repository'
import { Auth } from './auth'
import { SqlReport } from './sql-report'
import { Application } from 'egg'

export class UnitOfWork {
  app: Application
  sqlReport: SqlReport
  auth: Auth
  User: Repository
  Setting: Repository

  constructor(app: Application) {
    this.app = app

    // 查找所有Egg定义的model，并生成对应的sequelize model的repository
    // 所有在app/model中定义的sequelize model，egg都会自动生成到 app.model.xxx，注意生成的对象用文件的 pascal 命名法
    Object.keys(app.model).forEach(key => {
      // 如果没有注册自定义repository，那么默认的repository类初始
      if (!this[key] && app.model[key].findAndCountAll) {
        this[key] = new Repository(this.app, key)
        // app.logger.info('uow constructor auto', key, this[key].model.name)
      }
    })
    // app.logger.info(Object.keys(this), this.PurchaseOrder.model.name)

    this.sqlReport = new SqlReport(app, this)
    this.auth = new Auth(app, this)
  }
}
